package drive.RemakeService.ServiceFormat;

import com.google.gson.Gson;
import drive.Mapper.*;
import drive.Model.*;
import drive.RemakeService.ServiceInterface.MarketItemService;
import drive.pojo.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class MarketItemServiceA implements MarketItemService {

    @Value("${official.account.id}")
    private int OFFICIAL_ACCOUNT_ID; // 官方账号ID，从配置文件中获取

    Gson gson = new Gson();

    @Autowired
    SecondHandItemMapper secondHandItemMapper;

    @Autowired
    ImageMapper imageMapper;

    @Autowired
    TransactionOrderMapper transactionOrderMapper;

    @Autowired
    ReportRecordMapper reportRecordMapper;

    @Autowired
    private ChatSessionMapper chatSessionMapper;

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Autowired
    private FavoriteRecordMapper favoriteRecordMapper;

    @Autowired
    private UserMapper userMapper;


    @Override
    @Transactional
    public String publishMarketItem(Secondhanditem item, List<String> img_url) {
        // 实现发布商品逻辑
        secondHandItemMapper.add(item);
        String[] img = img_url.toArray(new String[0]);
        for (int i = 0; i < img.length; i++) {
            Image image = new Image();
            image.setImageUrl(img[i]);
            image.setArticleID(item.getItemID());
            image.setIndexNo(i);
            image.setUploadTime(new Date());
            image.setImgType(Image.Status.item);
            imageMapper.add(image);
        }
        return "商品发布成功";
    }

    @Override
    public String browseMarketItems() {
        // 实现浏览商品逻辑
        return "商品浏览成功";
    }

    @Override
    @Transactional
    public String purchaseMarketItem(TransactionOrder transactionOrder) {
        // 实现购买商品逻辑
        Secondhanditem secondhanditem = secondHandItemMapper.findByItemID(transactionOrder.getItemID());
        secondhanditem.setStatus(Secondhanditem.Status.inTransaction);
        secondHandItemMapper.update(secondhanditem);
        transactionOrder.setStatus(TransactionOrder.Status.inProgress);
        transactionOrder.setCreationTime(new Date());
        transactionOrderMapper.add(transactionOrder);
        return "商品购买成功";
    }

    @Override
    @Transactional
    public String evaluateMarketTransaction(TransactionOrder transactionOrder) {
        // 实现评价交易逻辑
        transactionOrderMapper.update(transactionOrder);
        if(transactionOrder.getBuyerRating()!=0 && transactionOrder.getSellerRating()!=0){
            int buyerRating = transactionOrder.getBuyerRating();
            int sellerRating = transactionOrder.getSellerRating();
            User seller = userMapper.selectUserById(transactionOrder.getSellerID());
            User buyer = userMapper.selectUserById(transactionOrder.getBuyerID());
            int seller_score = seller.getCreditScore();
            int buyer_score = buyer.getCreditScore();
            buyerRating = Math.min(5,buyerRating);
            sellerRating = Math.min(5,sellerRating);
            buyerRating = Math.max(0,buyerRating);
            sellerRating = Math.max(0,sellerRating);
            int seller_update = seller_score-2+buyerRating;
            int buyer_update = buyer_score-2+sellerRating;
            seller.setCreditScore(seller_update);
            buyer.setCreditScore(buyer_update);
            userMapper.updateUser(seller);
            userMapper.updateUser(buyer);
        }
        return "交易评价成功";
    }

    @Override
    public String reportMarketItem(String token, Integer itemID, String reason) {
        // 实现举报商品逻辑
        int userID = JwtUtils.getuserID(token);
        ReportRecord reportRecord = new ReportRecord();
        reportRecord.setReporterID(userID);
        reportRecord.setReporteeID(itemID);
        reportRecord.setReportType(ReportRecord.ReportType.item);
        reportRecord.setReportReason(reason);
        reportRecord.setSubmissionTime(new Date());
        reportRecord.setReportStatus(ReportRecord.Status.pending);
        reportRecordMapper.add(reportRecord);
        return "商品举报成功";
    }

    /**
     * 根据时间分页查询商品
     * @param start_time 开始时间
     * @param end_time 结束时间
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 包含商品列表和分页信息的JSON字符串
     */
    @Override
    public String getItemsByTime(String start_time, String end_time, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<Secondhanditem> items = secondHandItemMapper.getItemsByTime(start_time, end_time, offset, pageSize);
        int total = secondHandItemMapper.getItemsByTimeCount(start_time, end_time);

        return gson.toJson("{"
                + "\"status\":\"success\","
                + "\"data\":" + gson.toJson(items) + ","
                + "\"total\":" + total + ","
                + "\"pageNum\":" + pageNum + ","
                + "\"pageSize\":" + pageSize
                + "}");
    }

    /**
     * 根据商品ID获取商品的第一张图片
     * @param itemID 商品ID
     * @return 包含图片信息的JSON字符串
     */
    @Override
    public String getFirstImageByItemID(int itemID) {
        Image image = imageMapper.getFirstImageByItemID(itemID,"item");
        if (image == null) {
            return gson.toJson("{\"status\":\"error\",\"message\":\"该商品没有图片\"}");
        }
        return gson.toJson(image);
    }

    @Override
    public String getImageByItemID(int itemID) {
        List<Image> image = imageMapper.getImageByItemID(itemID,"item");
        if (image == null) {
            return gson.toJson("{\"status\":\"error\",\"message\":\"该商品没有图片\"}");
        }
        return gson.toJson(image);
    }

    /**
     * 通过关键词检索商品
     * @param keyword 关键词
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 包含商品列表和分页信息的JSON字符串
     */
    @Override
    public String searchItems(String keyword, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<Secondhanditem> items = secondHandItemMapper.searchItems(keyword, offset, pageSize);
        int total = secondHandItemMapper.searchItemsCount(keyword);

        return gson.toJson("{"
                + "\"status\":\"success\","
                + "\"data\":" + gson.toJson(items) + ","
                + "\"total\":" + total + ","
                + "\"pageNum\":" + pageNum + ","
                + "\"pageSize\":" + pageSize
                + "}");
    }

    /**
     * 根据商品ID创建会话
     * @param user1ID 用户1的ID
     * @param user2ID 用户2的ID
     * @param itemID 商品ID
     * @return 包含会话信息的JSON字符串
     */
    @Override
    public String createChatSessionByItem(int user1ID, int user2ID, int itemID) {
        // 检查是否已经存在会话
        ChatSession existingChatSession = chatSessionMapper.findByUserIDs(user1ID, user2ID);
        if (existingChatSession != null) {
            return gson.toJson("{"
                    + "\"status\":\"error\","
                    + "\"message\":\"会话已存在\""
                    + "}");
        }

        // 创建新的会话
        ChatSession chatSession = new ChatSession();
        chatSession.setUser1ID(user1ID);
        chatSession.setUser2ID(user2ID);
        chatSession.setCreationTime(new Date());
        chatSession.setItemId(itemID);// 关联商品ID
        chatSession.setUpdateTime(new Date());
        chatSessionMapper.add_item_session(chatSession);

        return gson.toJson("{"
                + "\"status\":\"success\","
                + "\"message\":\"会话创建成功\","
                + "\"chatSession\":" + gson.toJson(chatSession)
                + "}");
    }

    /**
     * 发送消息
     * @param chatRoomId 聊天室ID
     * @param senderId 发送者ID
     * @param content 消息内容
     * @return 操作结果的JSON字符串
     */
    @Transactional
    @Override
    public String sendMessage(int chatRoomId, int senderId, String content) {
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setChatSessionID(chatRoomId);
        chatMessage.setSenderID(senderId);
        chatMessage.setContent(content);
        chatMessage.setSendTime(new Date());
        chatMessage.setStatus(ChatMessage.Status.sending);

        chatMessageMapper.add(chatMessage);

        chatSessionMapper.update_time(chatRoomId);

        return gson.toJson("{"
                + "\"status\":\"success\","
                + "\"message\":\"消息发送成功\","
                + "\"timestamp\":\"" + new Date() + "\""
                + "}");
    }
    /**
     * 收藏商品
     * @param userId 用户ID
     * @param itemId 商品ID
     * @return 操作结果的JSON字符串
     */
    @Transactional
    @Override
    public String favoriteItem(int userId, int itemId) {
        // 检查是否已经收藏
        FavoriteRecord favoriteRecord = favoriteRecordMapper.findByUserIDAndItemID(userId, itemId);
        if (favoriteRecord != null) {
            return gson.toJson("{"
                    + "\"status\":\"error\","
                    + "\"message\":\"您已经收藏过该商品\""
                    + "}");
        }

        // 创建收藏记录
        FavoriteRecord newFavoriteRecord = new FavoriteRecord();
        newFavoriteRecord.setUserID(userId);
        newFavoriteRecord.setContentID(itemId);
        newFavoriteRecord.setContentType(FavoriteRecord.Status.item);
        newFavoriteRecord.setCreationTime(new Date());

        favoriteRecordMapper.add(newFavoriteRecord);

        return gson.toJson("{"
                + "\"status\":\"success\","
                + "\"message\":\"收藏成功\","
                + "\"favoriteID\":" + newFavoriteRecord.getFavoriteID()
                + "}");
    }
    private void sendOfficialMessage(int authorId, String messageContent) {
        ChatSession chatSession = chatSessionMapper.findByUserIDs(OFFICIAL_ACCOUNT_ID,authorId);
        if (chatSession == null) {
            // 创建会话
            chatSession = new ChatSession();
            chatSession.setUser1ID(OFFICIAL_ACCOUNT_ID);
            chatSession.setUser2ID(authorId);
            chatSession.setCreationTime(new Date());
            chatSessionMapper.add(chatSession);
            System.out.println(chatSession);
        }
        System.out.println("发送关注消息中");
        // 发送消息
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setChatSessionID(chatSession.getChatSessionID());
        chatMessage.setSenderID(OFFICIAL_ACCOUNT_ID);
        chatMessage.setContent(messageContent);
        chatMessage.setSendTime(new Date());
        chatMessage.setStatus(ChatMessage.Status.sending);
        chatMessageMapper.add(chatMessage);

        chatSessionMapper.update_time(chatSession.getChatSessionID());
    }
}